YAHOO.namespace("pingmob");
YAHOO.namespace("pingmob.container");

YAHOO.util.Event.onDOMReady(function () {
    YAHOO.pingmob.cardList = function () {

        //formatter
        var periodTypeFormatter = function (elCell, oRecord) {
            if (oRecord.getData('cardValidityPeriodType') == 'Y') {
                elCell.innerHTML = "年";
            } else if (oRecord.getData('cardValidityPeriodType') == 'M') {
                elCell.innerHTML = "月";
            } else if (oRecord.getData('cardValidityPeriodType') == 'D') {
                elCell.innerHTML = "日";
            } else {
                elCell.innerHTML = "";
            }
        };

        var number_per_page_default = 50;

        var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event;

        var myPaginator = new YAHOO.widget.Paginator({
            containers:['cards-thread-paging','cards-thread-paging_top'],
            rowsPerPage:number_per_page_default,
            previousPageLinkClass:"yui-pg-previous gc-inbox-prev",
            nextPageLinkClass:"yui-pg-next gc-inbox-next"//,
            //template           : "<strong>{CurrentPageReport}</strong> {PreviousPageLink} {NextPageLink}",
            //pageReportTemplate : "{startIndex}-{endIndex} of {totalRecords}"
        });
        var myTableConfig = {
            paginator:myPaginator,
            MSG_EMPTY:messages["js.no.records.found"],
            dynamicData:true,
            initialLoad:false,
            width:'100%'
        };

        var formatDate = function(elCell, oRecord, oColumn, oData) {
            if (oData!=null && oData!="") {
                var oDate = new Date(oData);
                elCell.innerHTML = YAHOO.util.Date.format(oDate, {format:"%Y-%m-%d"});
            }
        };

        var myColumnDefs = [
            {key:"Select", label:"", formatter:"checkbox", className:"table-checkbox"},
            {key:"id", label:"ID", sortable:true},
            {key: "batchId", label: '批次', sortable: true},
            {key: "cardId", label: '卡号', sortable: true},
            {key: "cardType", label: '类型', sortable: true},
            {key: "cardParValue", label: '星币值', sortable: true},
            {key: "cardActivationDeadline", label: '截止日期', sortable: true},
            {key: "cardValidityPeriodType", label: '有效期类型', formatter: periodTypeFormatter, sortable: true},
            {key: "cardValidityPeriod", label: '有效期长度', sortable: true},
            {key: "active", label: '激活状态', sortable: true, formatter:function (elCell, oRecord, oColumn, oData) {
                if(oData=="true"){
                    elCell.innerHTML ="已激活";
                }else{
                    elCell.innerHTML = "未激活";
                }
            }},
            {key: "cardStatus", label: '卡片状态', sortable: true, formatter:function (elCell, oRecord, oColumn, oData) {
                var cardStatus = oRecord.getData("cardStatus");
                if(cardStatus!="" && cardStatus!=undefined){
                    elCell.innerHTML = messages[cardStatus];
                }else{
                    elCell.innerHTML = "";
                }
            }},
            {key: "agent", label: '代理商', sortable: true},
            {key: "dateAdded", label: '创建时间', sortable: true},
            {key: "updateBy", label: '最后更新者'},
            { label: '消费详情', className: "table-action", action: 'view', formatter: function (elCell, oRecord) {
                if (oRecord.getData('active')) {
                    elCell.innerHTML = '<img src="/static/images/edit.gif" title="消费详情" />';
                    elCell.style.cursor = 'pointer';
                }
            }}
        ];
        var cardsDataSource = new YAHOO.util.DataSource('/ozing/cards.json?');
        cardsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        cardsDataSource.responseSchema = {
            resultsList:'records',
            metaFields:{
                totalRecords:'totalRecords',
                paginationRecordOffset:"startIndex",
                paginationRowsPerPage:"pageSize",
                sortKey: "sort",
                sortDir: "dir"
            }
        };

        var cardsDataTable = new YAHOO.widget.DataTable("cards-thread-list", myColumnDefs, cardsDataSource, myTableConfig);

        // Show loading message while page is being rendered
        cardsDataTable.showTableMessage(cardsDataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);

        // Add the instances to the YAHOO.example namespace for inspection
        YAHOO.pingmob.BHMIntegration_files = {
            myPaginator  : myPaginator,
            cardsDataSource : cardsDataSource,
            cardsDataTable  : cardsDataTable
        };

        // Integrate with Browser History Manager
        var History = YAHOO.util.History;

        // Define a custom function to route sorting through the Browser History Manager
        var handleSorting = function (oColumn) {
            // Calculate next sort direction for given Column
            var sDir = this.getColumnSortDir(oColumn);

            // The next state will reflect the new sort values
            // while preserving existing pagination rows-per-page
            // As a best practice, a new sort will reset to page 0
            var newState = generateRequest(0, oColumn.key, sDir, this.get("paginator").getRowsPerPage());

            // Pass the state along to the Browser History Manager
            History.navigate("cardTable", newState);
        };
        cardsDataTable.sortColumn = handleSorting;

        // Define a custom function to route pagination through the Browser History Manager
        var handlePagination = function (state) {
            // The next state will reflect the new pagination values
            // while preserving existing sort values
            // Note that the sort direction needs to be converted from DataTable format to server value
            var sortedBy  = this.get("sortedBy"),
                newState = generateRequest(
                    state.recordOffset, sortedBy.key, sortedBy.dir, state.rowsPerPage
                );

            // Pass the state along to the Browser History Manager
            History.navigate("cardTable", newState);
        };

        // First we must unhook the built-in mechanism...
        myPaginator.unsubscribe("changeRequest", cardsDataTable.onPaginatorChangeRequest);
        // ...then we hook up our custom function
        myPaginator.subscribe("changeRequest", handlePagination, cardsDataTable, true);

        // Update totalRecords on the fly with values from server
        cardsDataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
            var meta = oResponse.meta;
            oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
            oPayload.pagination = {
                rowsPerPage:meta.paginationRowsPerPage || number_per_page_default,
                recordOffset:meta.paginationRecordOffset || 0
            };
            if(oPayload.totalRecords==undefined){
                oPayload.totalRecords=0;
            }
            oPayload.sortedBy = {
                key: meta.sortKey || "id",
                dir: (meta.sortDir) ? "yui-dt-" + meta.sortDir : "yui-dt-asc" // Convert from server value to DataTable format
            };
            return true;
        };

        var generateRequest = function (startIndex,sortKey,dir,results) {
            startIndex = startIndex || 0;
            sortKey   = sortKey || "id";
            dir   = (dir) ? dir.substring(7) : "desc"; // Converts from DataTable format "yui-dt-[dir]" to server value "[dir]"
            results   = results || number_per_page_default;

            return  "sort=" + sortKey + "&dir=" + dir +
                "&start_index=" + startIndex + "&num_per_page=" + results + "&timestamp=" + new Date().getTime() +
                "&cardType=" + $('#cardType').val() + "&cardId=" + $('#cardId').val() + "&cardPassword=" + $('#cardPassword').val() +
                "&activeStartDate=" + $('#activeStartDate').val() + "&activeEndDate=" + $('#activeEndDate').val() +
                "&cardStatus=" + $('#cardStatus').val() +  "&agent=" + $('#agent').val() +  "&batchId=" + $('#batchId').val();
        };

        // Called by Browser History Manager to trigger a new state
        var handleHistoryNavigation = function (request) {
            //show the "loading" message.
            cardsDataTable.getTbodyEl().style.display = "none";
            cardsDataTable.showTableMessage(messages["js.loading"]);

            // Sends a new request to the DataSource
            cardsDataSource.sendRequest(request, {
                success:function () {
                    checkCardsAll_btn.set("checked", false); //uncheck all.
                    cardsDataTable.getTbodyEl().style.display = "";
                    cardsDataTable.hideTableMessage();
                    cardsDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                failure:function () {
                    checkCardsAll_btn.set("checked", false); //uncheck all.
                    cardsDataTable.getTbodyEl().style.display = "";
                    cardsDataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                    cardsDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                scope:cardsDataTable,
                argument:{} // Pass in container for population at runtime via doBeforeLoadData
            });
        };

        // Calculate the first request
        var initialRequest = History.getBookmarkedState("cardTable") || // Passed in via URL
            generateRequest(); // Get default values

        // Register the module
        History.register("cardTable", initialRequest, handleHistoryNavigation);

        // Render the first view
        History.onReady(function () {
            // Current state after BHM is initialized is the source of truth for what state to render
            var currentState = History.getCurrentState("cardTable");
            handleHistoryNavigation(currentState);
        });

        var renderPage = function () {
            var currentState = History.getCurrentState("cardTable") || generateRequest();
            handleHistoryNavigation(currentState);
        };

        var searchPage = function () {
            var currentState =  generateRequest();
            handleHistoryNavigation(currentState);
        };

        // Initialize the Browser History Manager.
        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

        cardsDataTable.subscribe('cellClickEvent', function (ev) {
            var target = YAHOO.util.Event.getTarget(ev);
            var column = this.getColumn(target);
            var record = this.getRecord(target);
            if (column.action == 'view' && record.getData('active')) {
                window.location.href = "/ozing/card?cardId=" + record.getData("cardId");
            } else {
                //do nothing
            }
        });

        /*
         var refreshCardThread = function (p_oEvent) {
         searchPage();
         };
         */

        var getSlectedCardIds = function(){
            var currentPageUrl = History.getCurrentState("cardTable")||generateRequest();
            var start_index = parseInt(getRequestValueFromURL(currentPageUrl, "start_index"));
            var oRows = cardsDataTable.getSelectedRows();
            var oRS = cardsDataTable.getRecordSet();
            var cards_ids = "";
            for (var i = start_index; i < oRS.getLength(); i++) {
                var oRec = oRS.getRecord(i);
                if (oRec.getData("Select")) {
                    cards_ids += oRec.getData("cardId");
                    cards_ids += ",";
                }
            }
            return cards_ids;
        };

        var batchCardStatus=function(p_oEvent){
            var cards_ids = getSlectedCardIds();
            if (cards_ids != "" && confirm("确认批量修改?") && Dom.get("cardStatus_batch").value!="") {
                YAHOO.util.Connect.asyncRequest(
                    'GET',
                    '/admin/cards/status?cardIds=' + cards_ids+"&status="+Dom.get("cardStatus_batch").value,
                    {
                        success:function (o) {
                            if (o.responseText != "") {
                                alert("设置卡片状态成功.");
                                searchPage();

                            }
                        },
                        failure:function (o) {
                            alert(o.statusText);
                        },
                        scope:this
                    }
                );
                YAHOO.pingmob.container.panel_status.hide();
            }
        };
        var batchAgent=function(p_oEvent){
            var cards_ids = getSlectedCardIds();
            if (cards_ids != "" && confirm("确认批量修改?") && Dom.get("agent_batch").value!="") {
                YAHOO.util.Connect.asyncRequest(
                    'GET',
                    '/admin/cards/agent?'+encodeURI('cardIds=' + cards_ids+"&agent="+Dom.get("agent_batch").value),
                    {
                        success:function (o) {
                            if (o.responseText != "") {
                                alert("设置代理商成功.");
                                searchPage();

                            }
                        },
                        failure:function (o) {
                            alert(o.statusText);
                        },
                        scope:this
                    }
                );
                YAHOO.pingmob.container.panel_agent.hide();
            }
        };

        var handleCancel = function() {
            this.cancel();
        };

        YAHOO.pingmob.container.panel_status = new YAHOO.widget.Dialog("panel_status", {width:"600px", visible:false, fixedcenter : true,
            underlay:"shadow",
            modal:true,
            buttons : [ { text:"确定", handler:batchCardStatus},
                { text:"取消", handler:handleCancel } ]});
        YAHOO.pingmob.container.panel_status.render();

        var show_status_panel = function(){
            //check selected products.
            if (!batchCardStatus_btn.get("disabled")) {
                var oRows = cardsDataTable.getSelectedRows();
                if (oRows.length < 1) {
                    alert("请选择卡片.");
                } else {
                    Dom.setStyle("panel_status", "display", "");
                    YAHOO.pingmob.container.panel_status.show();
                }
            }
        };

        var batchCardStatus_btn = new YAHOO.widget.Button("batchCardStatus",{disabled:true});
        YAHOO.util.Event.addListener("batchCardStatus", "click", show_status_panel, YAHOO.pingmob.container.panel_status, true);

        YAHOO.pingmob.container.panel_agent = new YAHOO.widget.Dialog("panel_agent", {width:"600px", visible:false, fixedcenter : true,
            underlay:"shadow",
            modal:true,
            buttons : [ { text:"确定", handler:batchAgent},
                { text:"取消", handler:handleCancel } ]});
        YAHOO.pingmob.container.panel_agent.render();

        var show_agent_panel = function(){
            //check selected products.
            if (!batchAgent_btn.get("disabled")) {
                var oRows = cardsDataTable.getSelectedRows();
                if (oRows.length < 1) {
                    alert("请选择卡片.");
                } else {
                    Dom.setStyle("panel_agent", "display", "");
                    YAHOO.pingmob.container.panel_agent.show();
                }
            }
        };

        var batchAgent_btn = new YAHOO.widget.Button("batchAgent");
        YAHOO.util.Event.addListener("batchAgent", "click", show_agent_panel, YAHOO.pingmob.container.panel_agent, true);

        //button.
        // var refreshCardsThread_btn = new YAHOO.widget.Button("refreshCardsThread", { onclick:{ fn:refreshCardThread } });
        var checkCardsAll_btn = new YAHOO.widget.Button("selectCardsAll", { label:messages["select.all"], checked:false });
        var query_btn = new YAHOO.widget.Button("query_cards_btn", {label:messages["button.search"],onclick:{ fn:searchPage } });

        cardsDataTable.subscribe('checkboxClickEvent', function (oArgs) {
            var currentPageUrl = History.getCurrentState("cardTable")||generateRequest();
            var start_index = parseInt(getRequestValueFromURL(currentPageUrl, "start_index"));
            var elCheckbox = oArgs.target;
            var newValue = elCheckbox.checked;
            var record = this.getRecord(elCheckbox);
            var column = this.getColumn(elCheckbox);
            record.setData(column.key, newValue);

            var allChecked = true;
            var oRS = cardsDataTable.getRecordSet();
            for (var i = start_index; i < oRS.getLength(); i++) {
                var oRec = oRS.getRecord(i);
                if (!oRec.getData('Select')) {
                    allChecked = false;
                    break;
                }
            }
            checkCardsAll_btn.set("checked", allChecked);
            if (newValue) {
                this.selectRow(record);
            } else {
                this.unselectRow(record);
            }
            if (cardsDataTable.getSelectedRows().length > 0) {
                batchCardStatus_btn.set("disabled", false);
                batchAgent_btn.set("disabled", false);
            } else {
                batchCardStatus_btn.set("disabled", true);
                batchAgent_btn.set("disabled", true);
            }
            return false;
        });

        checkCardsAll_btn.on("click", function (e) {
            var currentPageUrl = History.getCurrentState("cardTable")||generateRequest();
            var start_index = parseInt(getRequestValueFromURL(currentPageUrl, "start_index"));
            var check = checkCardsAll_btn.get("checked");
            var oRS = cardsDataTable.getRecordSet();
            for (var i = start_index; i < oRS.getLength(); i++) {
                var oRec = oRS.getRecord(i);
                oRec.setData('Select', check);
                if (check) {
                    cardsDataTable.selectRow(oRec);
                } else {
                    cardsDataTable.unselectRow(oRec);
                }
            }
            cardsDataTable.render();
            if (cardsDataTable.getSelectedRows().length > 0) {
                batchCardStatus_btn.set("disabled", false);
                batchAgent_btn.set("disabled", false);
            } else {
                batchCardStatus_btn.set("disabled", true);
                batchAgent_btn.set("disabled", true);
            }
        });

        return {
            ds:cardsDataSource,
            dt:cardsDataTable
        };

    }();
});
